<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>KSpace-Client 浏览器示例</title>
  <style>
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      line-height: 1.6;
      color: #333;
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
    }
    h1, h2 {
      color: #2c3e50;
    }
    .container {
      background: #f8f9fa;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    input[type="file"] {
      margin-bottom: 10px;
    }
    button {
      background: #007bff;
      color: white;
      border: none;
      padding: 8px 16px;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
    }
    button:hover {
      background: #0056b3;
    }
    .progress-bar {
      width: 100%;
      height: 20px;
      background: #e9ecef;
      border-radius: 10px;
      overflow: hidden;
      margin: 10px 0;
    }
    .progress-fill {
      height: 100%;
      background: #28a745;
      transition: width 0.3s ease;
      text-align: center;
      line-height: 20px;
      color: white;
      font-size: 12px;
    }
    .result {
      background: #e3f2fd;
      border-left: 4px solid #2196f3;
      padding: 10px;
      margin: 10px 0;
      border-radius: 4px;
      font-family: monospace;
      white-space: pre-wrap;
      word-break: break-all;
      max-height: 300px;
      overflow-y: auto;
    }
    .info {
      background: #fff3cd;
      border-left: 4px solid #ffc107;
      padding: 10px;
      margin: 10px 0;
      border-radius: 4px;
    }
    .error {
      background: #f8d7da;
      border-left: 4px solid #dc3545;
      padding: 10px;
      margin: 10px 0;
      border-radius: 4px;
      color: #721c24;
    }
  </style>
</head>
<body>
  <h1>KSpace-Client 浏览器示例</h1>
  
  <div class="info">
    <strong>提示：</strong>在使用前，请确保已构建SDK并引入正确的文件路径。示例中的配置信息需要替换为实际的OSS服务配置。
  </div>

  <div class="container">
    <h2>1. 单个文件上传</h2>
    <input type="file" id="singleFileInput" />
    <button id="uploadSingleBtn">上传文件</button>
    <div class="progress-bar" id="singleProgressBar">
      <div class="progress-fill" style="width: 0%">0%</div>
    </div>
    <div id="singleUploadResult" class="result"></div>
  </div>

  <div class="container">
    <h2>2. 批量文件上传</h2>
    <input type="file" id="multipleFileInput" multiple />
    <button id="uploadMultipleBtn">批量上传</button>
    <div id="multipleUploadStatus"></div>
    <div id="multipleUploadResult" class="result"></div>
  </div>

  <div class="container">
    <h2>3. 获取文件信息</h2>
    <input type="text" id="fileKeyInput" placeholder="输入文件路径" />
    <button id="getFileInfoBtn">获取信息</button>
    <div id="fileInfoResult" class="result"></div>
  </div>

  <div class="container">
    <h2>4. 删除文件</h2>
    <input type="text" id="deleteFileKeyInput" placeholder="输入文件路径" />
    <button id="deleteFileBtn">删除文件</button>
    <div id="deleteFileResult" class="result"></div>
  </div>

  <div class="container">
    <h2>5. 生成文件URL</h2>
    <input type="text" id="urlFileKeyInput" placeholder="输入文件路径" />
    <div>
      <label>
        <input type="checkbox" id="addExpiryCheckbox" />
        添加过期时间（小时）
      </label>
      <input type="number" id="expiryHoursInput" min="1" max="720" value="24" disabled />
    </div>
    <button id="generateUrlBtn">生成URL</button>
    <div id="fileUrlResult" class="result"></div>
  </div>

  <!-- 这里应该引入构建后的SDK文件 -->
  <!-- <script src="../dist/kspace-client.js"></script> -->
  
  <script>
    // 注意：在实际使用时，应该引入构建后的SDK文件
    // 这里使用模拟代码来演示使用方式
    
    // 模拟 KSpaceClient 类（实际使用时应该从SDK中导入）
    class MockKSpaceClient {
      constructor(config) {
        this.config = config;
        console.log('KSpaceClient 已初始化，配置:', config);
      }
      
      async upload(options) {
        return new Promise((resolve) => {
          // 模拟上传进度
          let progress = 0;
          const interval = setInterval(() => {
            progress += 10;
            if (options.onProgress) {
              options.onProgress(progress, 100, progress);
            }
            if (progress >= 100) {
              clearInterval(interval);
              // 模拟上传成功
              resolve({
                key: options.key,
                url: `https://${this.config.bucket}.${this.config.endpoint}/${options.key}`,
                size: 1024,
                uploadedAt: Date.now(),
                etag: '"mock-etag-value"'
              });
            }
          }, 200);
        });
      }
      
      async uploadFiles(files) {
        const results = [];
        for (const file of files) {
          const result = await this.upload(file);
          results.push(result);
        }
        return results;
      }
      
      async getFileInfo(key) {
        return {
          key,
          size: 1024,
          lastModified: new Date(),
          etag: '"mock-etag-value"',
          contentType: 'image/jpeg',
          storageClass: 'Standard'
        };
      }
      
      async deleteFile(key) {
        return true;
      }
      
      getFileUrl(key, expires) {
        let url = `https://${this.config.bucket}.${this.config.endpoint}/${key}`;
        if (expires) {
          url += `?Expires=${Math.floor(Date.now() / 1000) + expires}`;
        }
        return url;
      }
    }
    
    // 初始化客户端（使用模拟类）
    const client = new MockKSpaceClient({
      endpoint: 'oss.example.com',
      accessKeyId: 'your-access-key-id',
      accessKeySecret: 'your-access-key-secret',
      bucket: 'your-bucket-name',
      region: 'us-west-1',
      secure: true
    });

    // 1. 单个文件上传
    document.getElementById('uploadSingleBtn').addEventListener('click', async () => {
      const fileInput = document.getElementById('singleFileInput');
      const file = fileInput.files?.[0];
      const resultElement = document.getElementById('singleUploadResult');
      const progressBar = document.getElementById('singleProgressBar').querySelector('.progress-fill');
      
      if (!file) {
        resultElement.textContent = '请选择要上传的文件';
        resultElement.className = 'result error';
        return;
      }
      
      try {
        resultElement.textContent = '开始上传...';
        resultElement.className = 'result';
        progressBar.style.width = '0%';
        progressBar.textContent = '0%';
        
        const result = await client.upload({
          file,
          key: `browser-uploads/${Date.now()}-${file.name}`,
          storageClass: 'Standard',
          meta: {
            description: '浏览器上传的文件',
            userAgent: navigator.userAgent
          },
          onProgress: (progress) => {
            progressBar.style.width = `${progress}%`;
            progressBar.textContent = `${progress}%`;
          }
        });
        
        resultElement.textContent = JSON.stringify(result, null, 2);
        resultElement.className = 'result';
        
      } catch (error) {
        resultElement.textContent = `上传失败: ${error.message || error}`;
        resultElement.className = 'result error';
      }
    });

    // 2. 批量文件上传
    document.getElementById('uploadMultipleBtn').addEventListener('click', async () => {
      const fileInput = document.getElementById('multipleFileInput');
      const files = Array.from(fileInput.files || []);
      const statusElement = document.getElementById('multipleUploadStatus');
      const resultElement = document.getElementById('multipleUploadResult');
      
      if (files.length === 0) {
        resultElement.textContent = '请选择要上传的文件';
        resultElement.className = 'result error';
        return;
      }
      
      try {
        statusElement.textContent = `开始上传 ${files.length} 个文件...`;
        resultElement.textContent = '';
        
        const uploadPromises = files.map(async (file, index) => {
          const result = await client.upload({
            file,
            key: `browser-uploads/${Date.now()}-${index}-${file.name}`,
            onProgress: (progress) => {
              statusElement.textContent = `上传中... (${index + 1}/${files.length}) - ${progress}%`;
            }
          });
          return result;
        });
        
        const results = await Promise.all(uploadPromises);
        
        statusElement.textContent = '批量上传完成！';
        resultElement.textContent = JSON.stringify(results, null, 2);
        resultElement.className = 'result';
        
      } catch (error) {
        resultElement.textContent = `上传失败: ${error.message || error}`;
        resultElement.className = 'result error';
      }
    });

    // 3. 获取文件信息
    document.getElementById('getFileInfoBtn').addEventListener('click', async () => {
      const fileKeyInput = document.getElementById('fileKeyInput');
      const fileKey = fileKeyInput.value.trim();
      const resultElement = document.getElementById('fileInfoResult');
      
      if (!fileKey) {
        resultElement.textContent = '请输入文件路径';
        resultElement.className = 'result error';
        return;
      }
      
      try {
        resultElement.textContent = '获取文件信息中...';
        const fileInfo = await client.getFileInfo(fileKey);
        resultElement.textContent = JSON.stringify(fileInfo, null, 2);
        resultElement.className = 'result';
        
      } catch (error) {
        resultElement.textContent = `获取失败: ${error.message || error}`;
        resultElement.className = 'result error';
      }
    });

    // 4. 删除文件
    document.getElementById('deleteFileBtn').addEventListener('click', async () => {
      const fileKeyInput = document.getElementById('deleteFileKeyInput');
      const fileKey = fileKeyInput.value.trim();
      const resultElement = document.getElementById('deleteFileResult');
      
      if (!fileKey) {
        resultElement.textContent = '请输入文件路径';
        resultElement.className = 'result error';
        return;
      }
      
      try {
        resultElement.textContent = '删除中...';
        const success = await client.deleteFile(fileKey);
        
        if (success) {
          resultElement.textContent = `文件 ${fileKey} 删除成功`;
        } else {
          resultElement.textContent = `文件 ${fileKey} 删除失败`;
          resultElement.className = 'result error';
        }
        
      } catch (error) {
        resultElement.textContent = `删除失败: ${error.message || error}`;
        resultElement.className = 'result error';
      }
    });

    // 5. 生成文件URL
    document.getElementById('addExpiryCheckbox').addEventListener('change', (e) => {
      document.getElementById('expiryHoursInput').disabled = !e.target.checked;
    });

    document.getElementById('generateUrlBtn').addEventListener('click', () => {
      const fileKeyInput = document.getElementById('urlFileKeyInput');
      const fileKey = fileKeyInput.value.trim();
      const addExpiryCheckbox = document.getElementById('addExpiryCheckbox');
      const expiryHoursInput = document.getElementById('expiryHoursInput');
      const resultElement = document.getElementById('fileUrlResult');
      
      if (!fileKey) {
        resultElement.textContent = '请输入文件路径';
        resultElement.className = 'result error';
        return;
      }
      
      try {
        let url;
        if (addExpiryCheckbox.checked) {
          const expiryHours = parseInt(expiryHoursInput.value) || 24;
          url = client.getFileUrl(fileKey, expiryHours * 3600);
        } else {
          url = client.getFileUrl(fileKey);
        }
        
        resultElement.textContent = url;
        resultElement.className = 'result';
        
      } catch (error) {
        resultElement.textContent = `生成失败: ${error.message || error}`;
        resultElement.className = 'result error';
      }
    });
  </script>
</body>
</html>